﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Hosting;
using MyX.Core;
using SimpleFile;

namespace LearningEnglish.Models
{
    /// <summary>
    /// 提供对各种类型上传文件的处理方法
    /// </summary>
    public class UploadFile
    {
        /// <summary>
        /// 创建能接收图片文件类型的处理类
        /// </summary>
        /// <returns></returns>
        public static UploadFile AcceptImgFile()
        {
            return new UploadFile(new FileFilter("~/StaticFiles/Img", true, "jpg", "png"));
        }

        public static UploadFile AcceptAudioFile()
        {
            return new UploadFile(new FileFilter("~/StaticFiles/Audio", true, "mp3"));
        }


        public UploadFile(FileFilter fileFilter)
            : base()
        {
            _filter = fileFilter;
            Count = 0;
            SaveFiles = new List<string>();
        }

        /// <summary>
        /// 保存文件到指定目录
        /// <para>当文件数为0，保存错误时，都会抛出异常</para>
        /// <para>当保存出现异常时，都会回滚，将该次保存的文件全部删除，确保没有错误文件存留</para>
        /// </summary>
        /// <exception cref="System.Exception"></exception>
        /// <param name="files"></param>
        public void Save(HttpFileCollectionBase files)
        {
            Check(files);
            Clear();

            try
            {
                //为测试该类，请勿用Foreach直接迭代，而应该通过Key
                //这是因为.net中的实现，和测试用实现并不一致，但AllKeys的行为表现可以模拟成一致
                var keys = files.AllKeys;
                foreach (string key in keys)
                {
                    SaveFile(files[key]);
                }
            }
            catch (Exception)
            {
                RollBack();
                Clear();
                throw;
            }
            foreach (var info in SaveFiles)
            {
                FileService.Instance.AddLocalFile(info);
            }
        }

        private void Clear()
        {
            Count = 0;
            SaveFiles.Clear();
        }

        private void Check(HttpFileCollectionBase files)
        {
            if (files == null || files.Count == 0)
                throw new UploadFileSaveException("无待保存文件");
            var keys = files.AllKeys;
            foreach (var key in keys)
            {
                var file = files[key];
                var extension = Path.GetExtension(file.FileName);
                if (!_filter.Accept(extension))
                    throw new UploadFileSaveException("该文件后缀名不允许保存 " + extension);
            }
        }

        private void SaveFile(HttpPostedFileBase file)
        {

            var fileID = Guid.NewGuid();
            var filePath = Path.Combine(HostingEnvironment.MapPath(_filter.ServerDirectory), fileID.ToString() + Path.GetExtension(file.FileName));
            //保存文件
            file.SaveAs(filePath);

            //保存文件信息
            SaveFiles.Add(filePath);
        }

        private void RollBack()
        {
            foreach (var file in SaveFiles)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception) { }
            }
        }
        /// <summary>
        /// 本次保存的文件数
        /// </summary>
        public int Count
        {
            get;
            private set;
        }

        /// <summary>
        /// 本次保存的文件
        /// </summary>
        public List<string> SaveFiles
        {
            get;
            private set;
        }

        private FileFilter _filter;
    }

    public class UploadFileSaveException : Exception
    {
        public UploadFileSaveException(string message)
            : base(message)
        { }
    }
}